"""
    店小秘物流追踪任务
"""
import json
import time

from api.dxm.logistics import *
from helper.dxm.logistics import *
from pyboot.utils.date import DateUtils
from robot.dingding import DingRobot
from config.robot import robot_config
from dao.operation_shop import get_phone_by_platform_and_shop

# 物流状态通知钉钉机器人
ding_robot = DingRobot.get_instance(robot_config.ding['dxm']['OperationalLogisticsNotification'])

# 机器人请求体
robot_data = {
    "at": {
        "atMobiles": [],
        "isAtAll": False
    },
    "text": {
        "content": ""
    },
    "msgtype": "text"
}


def handle_logistics(state_type):
    """
    处理物流追踪列表逻辑装饰器
    :param state_type: 物流追踪类型
    :return:
    """

    def decorator(func):
        def wrapper(*args, **kwargs):
            index_logistics_html = page_order_logistics_list_api(state_type)
            page_total = get_logistics_total(index_logistics_html)
            # 每一页的html代码
            logistics_page_html = index_logistics_html
            # 循环页数获取所有(从第二页开始起第一页获取过了)
            for i in range(page_total):
                if i != 0:
                    # 不是第一页获取新的
                    logistics_page_html = page_order_logistics_list_api('pickup', i + 1)
                # 获取对应的数据
                logistics_list = get_logistics_list(logistics_page_html)
                # 循环数据
                for logistics in logistics_list:
                    func(logistics)

        return wrapper

    return decorator


@handle_logistics(state_type='pickup')
def task_001(logistics):
    """
    在“物流追踪”--“到达待取”中，
    筛选物流信息中最后一条，
    物流信息最后一条时间与正在筛选时间作对比，
    大于24小时的，抓取该订单的包裹号，
    需要推送到钉钉群，@相关店铺负责人，告知该包裹号订单：包裹已到达待取，需要联系买家
    :return:
    """
    # 两秒拿一条
    time.sleep(2)
    # 获取订单详情
    first_detail_date = json.loads(get_order_logistics_detail_by_tracking_api(
        tracking_number=logistics['tracking_number'],
        carrier_code=logistics['carrier_code']
    )['originaInfo'])[0]['Date']
    # 比较当前时间是否大于24小时
    time_calc = DateUtils.get_current_timestamp() - DateUtils.datetime_to_timestamp(
        DateUtils.parse_datetime(first_detail_date, format_str="%Y-%m-%d %H:%M")
    )
    # 判断是否过去24小时
    if time_calc > 24 * 60 * 60:
        platform_name = logistics['platform_name']
        shop_name = logistics['shop_name']
        # 根据平台加店铺的方式获取店铺负责人的电话发送钉钉消息
        phone_result = get_phone_by_platform_and_shop(platform_name, shop_name)
        # 确保 phone_result 不为空并且有至少一个结果
        if phone_result and phone_result[0]:
            phone = phone_result[0][0]
        else:
            phone = ""
        # 发送消息
        msg = f"平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，到达待取"
        if phone:
            robot_data['at']['atMobiles'] = [phone]
            robot_data['at']['isAtAll'] = False
            robot_data['text']['content'] = msg
            ding_robot.send_msg(robot_data)
        else:
            msg = f"该包裹找不负责人手机号---平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，到达待取"
            # 艾特所有人
            robot_data['at']['isAtAll'] = True
            robot_data['at']['atMobiles'] = []
            robot_data['text']['content'] = msg
            ding_robot.send_msg(robot_data)


@handle_logistics(state_type="undelivered")
def task_002(logistics):
    """
    在“物流追踪”--“投递失败”中，抓取该订单的包裹号，需要推送到钉钉群，@相关店铺负责人，告知该包裹号订单：包裹已投递失败，需要联系买家
    :return:
    """

    platform_name = logistics['platform_name']
    shop_name = logistics['shop_name']
    # 根据平台加店铺的方式获取店铺负责人的电话发送钉钉消息
    phone_result = get_phone_by_platform_and_shop(platform_name, shop_name)
    # 确保 phone_result 不为空并且有至少一个结果
    if phone_result and phone_result[0]:
        phone = phone_result[0][0]
    else:
        phone = ""
    # 发送消息
    msg = f"平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，包裹已投递失败，需要联系买家"
    if phone:
        robot_data['at']['atMobiles'] = [phone]
        robot_data['at']['isAtAll'] = False
        robot_data['text']['content'] = msg
        ding_robot.send_msg(robot_data)
    else:
        msg = f"该包裹找不负责人手机号---平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，包裹已投递失败，需要联系买家"
        # 艾特所有人
        robot_data['at']['isAtAll'] = True
        robot_data['at']['atMobiles'] = []
        robot_data['text']['content'] = msg
        ding_robot.send_msg(robot_data)


@handle_logistics(state_type="exception")
def task_003(logistics):
    """
    在“物流追踪”--“有异常”中，抓取该订单的包裹号，需要推送到钉钉群，@相关店铺负责人，告知该包裹号订单：包裹物流异常，视情况开查
    :return:
    """
    platform_name = logistics['platform_name']
    shop_name = logistics['shop_name']
    # 根据平台加店铺的方式获取店铺负责人的电话发送钉钉消息
    phone_result = get_phone_by_platform_and_shop(platform_name, shop_name)
    # 确保 phone_result 不为空并且有至少一个结果
    if phone_result and phone_result[0]:
        phone = phone_result[0][0]
    else:
        phone = ""
    # 发送消息
    msg = f"平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，包裹物流异常，视情况开查"
    if phone:
        robot_data['at']['atMobiles'] = [phone]
        robot_data['at']['isAtAll'] = False
        robot_data['text']['content'] = msg
        ding_robot.send_msg(robot_data)
    else:
        msg = f"该包裹找不负责人手机号---平台：{platform_name}，店铺：{shop_name}，包裹号：{logistics['tracking_number']}，包裹物流异常，视情况开查"
        # 艾特所有人
        robot_data['at']['isAtAll'] = True
        robot_data['at']['atMobiles'] = []
        robot_data['text']['content'] = msg
        ding_robot.send_msg(robot_data)


# logistics模块任务映射字典
DXM_LOGISTICS_TASK_DICT = {
    "001": task_001,
    "002": task_002,
    "003": task_003
}
